<?php

namespace app\repository;

use app\popo\model\Category;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Arr;

class CategoryRepository
{
    public function listOf(array $categoryPageQueryDTO): LengthAwarePaginator
    {
        $name = Arr::get($categoryPageQueryDTO, "name");
        $page = Arr::get($categoryPageQueryDTO, "page");
        $pageSize = Arr::get($categoryPageQueryDTO, "pageSize", 5);
        $type = Arr::get($categoryPageQueryDTO, "type");
        return Category::query()->when($name, function (Builder $query) use ($name) {
            return $query->where("name", $name);
        })->when($type, function (Builder $query) use ($type) {
            return $query->where("type", $type);
        })->paginate($pageSize);
    }

    public function save(array $categoryDTO): void
    {
        (new Category($categoryDTO))->saveByDto();
    }

    public function deleteById(int $id): void
    {
        $this->getById($id)->delete();
    }

    public function getById(int $id): Category|null
    {
        return Category::find($id);
    }

    public function update(array $categoryDTO): void
    {
        $category = $this->getById(Arr::get($categoryDTO, "id"));
        $category->updateWith(Arr::except($categoryDTO, array("id")));
    }

    public function startOrStop(string $status, int $id): void
    {
        $category = $this->getById($id);
        $category->update(compact("status"));
    }

    public function getListByType($type=1): array
    {
        return Category::query()
            ->where("type", $type)
            ->where("status", 1)
            ->get()
            ->map(function (Category $category) {
                return [
                    "id" => $category->id,
                    "name" => $category->name,
                    "sort" => $category->sort,
                    "status" => $category->status,
                    "type" => $category->type,
                    "updateTime" => $category->update_time->format("Y-m-d H:i:s"),
                    "createTime" => $category->create_time->format("Y-m-d H:i:s"),
                    "updateUser" => $category->update_user,
                ];
            })->toArray();
    }
}